var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var goodsRouter = require('./routes/goods');
var bannerRouter = require('./routes/banner');
var loginRouter = require('./routes/login');
var goodsApi = require('./api/goods');
var userApi = require('./api/user');
const session = require("express-session")
const multer = require("multer");
const upload = multer({ dest: './public/upload' })

var app = express();

app.use(upload.any())

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: '加密因子',   // 加密信息，可以随便写
  resave: false,      // 强制保存session，默认为true，建议设置为false
  saveUninitialized: true,    // 强制将未初始化的session存储，默认为true，建议为true
  cookie: { maxAge: 1000 * 60 * 30 }    // 过期时间，毫秒数
}))

app.use('/api/goods', goodsApi);
app.use('/api/user', userApi);

// login不被守卫
app.use('/login', loginRouter);

// 登录守卫
app.all("*", (req,res,next)=>{
  // 解析cookie数据，进行守卫
  // if(req.cookies.isLogin === "ok" || req.url === "/login/action"){

  // 解析session数据，进行守卫
  if(req.session.isLogin === "ok" || req.url === "/login/action"){
    next();
  }else{
    res.redirect("/login");
  }
})

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/goods', goodsRouter);
app.use('/banner', bannerRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
